﻿CREATE TRIGGER [dbo].[triu_Payment]
	ON  [dbo].[t_Payment]
AFTER UPDATE
AS 

IF @@ROWCOUNT > 1 AND TRIGGER_NESTLEVEL(@@PROCID) = 1 BEGIN	RAISERROR('Update of multiple payments is not supported.',16,1)	ROLLBACK	RETURN END
IF TRIGGER_NESTLEVEL(OBJECT_ID('triu_Payment_StatusID')) >0 RETURN
IF TRIGGER_NESTLEVEL(@@PROCID) >1 RETURN
--IF EXISTS(SELECT * FROM t_Payment P INNER JOIN inserted i ON P.LoanID = i.LoanID) AND
--	 NOT EXISTS(SELECT * FROM deleted) BEGIN	RAISERROR('Direct payment insert is not supported.',16,1)	ROLLBACK	RETURN END

SET NOCOUNT ON;

PRINT OBJECT_NAME(@@PROCID)+'[Level:'+STR(TRIGGER_NESTLEVEL(@@PROCID))+']'

DECLARE @CI int EXEC @CI = sp__Context_SecurityOff 1
EXECUTE AS Login='AFC-HOME\SQLServer'

UPDATE t_Payment 
SET IsProcessed = 0 ,IsPrinBal = dbo.fs_StateParams_IsRecalcPrinBal(P.StatusID)
FROM t_Payment P INNER JOIN inserted i ON P.ID = i.ID

DECLARE @PaymentID int SELECT @PaymentID = ID FROM inserted
EXEC s_PaymentInsert @PaymentID

REVERT
EXEC sp__Context_SecurityOff @CI

GO
DISABLE TRIGGER [dbo].[triu_Payment]
    ON [dbo].[t_Payment];

